<template>
  <div  style="padding: 20px">
    <el-breadcrumb separator="/" style="margin-bottom: 20px">
      <el-breadcrumb-item >当前位置：</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a >用户管理</a></el-breadcrumb-item>
    </el-breadcrumb>
    <div v-loading.lock="loading" style="z-index: 100"  element-loading-text="拼命加载中"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(255, 255, 255, 1)">
    <el-card style="margin-bottom: 10px">
      <el-input style="width:200px" v-model="queryParams.username" size="small" placeholder="请输入用户名" clearable></el-input>
      <el-input style="width:200px" v-model="queryParams.role" size="small" placeholder="请输入角色" clearable></el-input>
      <el-button type="primary" icon="el-icon-search" size="small" @click="getUser">查询</el-button>
      <el-button type="success" icon="el-icon-plus" size="small" @click="open"  v-permission="'user:addorupdate'">新增</el-button>
    </el-card>
    <el-card style="min-height: 600px">
      <el-table
        :data="tableData"
        border
        style="width: 100%"  highlight-current-row :header-cell-style="headerCellStyle">
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column label="角色" prop="role"></el-table-column>
        <el-table-column label="余额" prop="balance"></el-table-column>
        <el-table-column label="头像">
          <template slot-scope="scope">
              <img v-if="scope.row.picture" :src="scope.row.picture" class="avatar" style="max-height: 100px;max-width: 150px">
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="300px"
          >
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-circle-plus"  @click="edit(scope.row)">编辑</el-button>
            <el-button type="warning" slot="reference"   size="mini" style="margin-left: 0px" icon="el-icon-delete-solid" @click="delete1(scope.row)">删除</el-button>
            <el-button type="danger" slot="reference"   size="mini" style="margin-left: 0px" icon="el-icon-delete-solid" @click="resetPass(scope.row)">重置密码</el-button>

          </template>
        </el-table-column>
      </el-table>
      <!--        分页-->
      <div class="pagination-container" style="text-align: center">
        <el-pagination
          class="pagiantion"
          v-show="total>0"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[3, 5, 10, 15]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
    <el-dialog :visible.sync="ifshow" :title="title" style="" custom-class="my-dialog">
      <el-form :model="adddata" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="adddata.username"></el-input>
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="adddata.balance"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <template>
            <el-select v-model="adddata.role" placeholder="请选择">
              <el-option
                v-for="item in roles"
                :key="item.name"
                :label="item.name"
                :value="item.flag">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="头像" >
          <template slot-scope="props">
            <el-upload
              class="upload-demo" ref="upload"
              :action="uploadAction"
              :show-file-list="false"
              :headers="{ 'userId': token,'token':userToken}"
              :on-success="handleAvatarSuccess"
              :limit="1"
              multiple
              :before-upload="beforeAvatarUpload">
              <img v-if="adddata.picture" :src="adddata.picture" class="avatar" style="height: 100px">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </template>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即提交</el-button>
          <el-button @click="ifshow=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--    删除-->
    <el-dialog :visible.sync="ifdelete" title="删除" width="500px">
      <div style="text-align: center;font-size: 20px">确定删除该数据?</div>
      <div style="text-align: center;margin-top: 20px">

        <el-button type="danger" @click="sure">确定</el-button>
        <el-button type="primary" @click="ifdelete=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "../utils/request";
import {dev as globalConfig} from "../../config";
export default {
  data(){
    return{
      loading: true,
      title:'',
      //数据
      adddata:{},
      //规则
      rules: {
        username: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        picture: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
      },
      userToken:localStorage.getItem("token"),
      token:'',
      ifshow:false,
      total:0,
      tableData:[{}],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username:undefined,
        role:undefined,
      },
      deleteid:'',
      ifdelete:false,
      roles:[],
    }
  },
  computed: {
    uploadAction() {
      return 'http://' + globalConfig.host + ':8090/upload/';
    }
  },
  created() {
    this.getUser()
  },
  methods:{
    sure(){
      let url='/deleteUserId'
      let param={
        id:this.deleteid
      }
      request.post(url,param).then(resp=>{
        if (resp.code===200){
          this.getUser()
          this.ifdelete=false
          this.message(resp.errorMessage,'success')
        }
      }).catch(err=>{
       if (err.message==='Request failed with status code 403'){
         this.message('您无权限操作','error')
       }else{
         this.message(err,'error')
       }

      })
    },
    // 重置密码
    resetPass(i){
      this.$prompt('请输入密码', '重置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        request.post('/user/resetPass',{password:value,id:i.id}).then(resp=>{
          if (resp.code===0){
            this.$message.success(resp.errorMessage)
          }
        })
      }).catch(() => {
      });
    },
    //删除
    delete1(i){
      this.ifdelete=true
      this.deleteid=i.id
    },
    //编辑
    edit(i){
      console.log(i)
      this.ifshow=true
      this.title='编辑用户'
      this.token=i.id
      this.adddata={
        id:i.id,
        username:i.username,
        balance:i.balance,
        picture:i.picture,
        role:i.role,
      }
    },
    open(){
      this.clear1()
      this.ifshow=true
      this.title='新增用户'
    },

    //清楚数据
    clear1(){
      this. adddata={}
    },
    //添加
    onSubmit(){
      let url='/addUser'
      request.post(url,this.adddata).then(resp=>{
        if (resp.code===200){
          this.getUser()
          this.ifshow=false

          this.message(resp.errorMessage,'success')
        }else {
          this.message(resp.errorMessage,'error')
        }
      }).catch(error => {
        if (error.response && error.response.status === 403) {
          this.message("您没有访问该资源的权限", 'error');
        } else {
          this.message("请求失败，请稍后重试", 'error');
        }
      });
    },
    //分页
    handleSizeChange(val){
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.getUser()
    },
    handleCurrentChange(val){
      this.queryParams.pageNum = val;
      this.getUser()
    },
    getUser(){
      let url='/getUser'
      request.post(url,this.queryParams).then(resp=>{
        if (resp.code===200){
          this.tableData=resp.list
          this.total=resp.total
          this.loading=false
        }
      }).catch(err=>{
        this.message('未登录或登录过期','error')
      })
      request.post('/getRole',this.queryParams).then(resp=>{
        let result=resp.data
        if (resp.code===200){
          this.roles=resp.list
        }
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isJPG2 = file.type === "image/jpg";
      const isPNG = file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isJPG && !isJPG2 && !isPNG ) {
        this.message("只支持jpg或png格式图片",'warning');
      }
      if (!isLt5M) {
        this.message("请上传5MB以内的图片!",'warning');
      }
      this.message("上传成功",'success');
      return (isJPG || isJPG2 || isPNG) && isLt5M;
    },
    handleAvatarSuccess(res, file) {

      this.$refs.upload.clearFiles(); //上传成功之后清除历史记录
      console.log(res.data)
      this.adddata.picture =res.data ;
      this.getUser()
    },
    headerCellStyle(column) {
      return { backgroundColor: '#C7E3FF',color: '#1f2f3d' }
    },
  }
}
</script>

<style scoped>
>>> .el-dialog__header {
  background-color: #66b1ff;
}
</style>
